package com.example.interview.ui.hundred

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.interview.databinding.FragmentHundredBinding
import com.example.interview.model.Question
import com.example.interview.utils.FileUtils
import org.json.JSONObject
import java.io.File
import java.io.FileWriter

class HundredFragment : Fragment() {

    private var _binding: FragmentHundredBinding? = null
    private val binding get() = _binding!!
    private val adapter = QuestionAdapter()
    private var previousAnswerLength = 0
    private var previousAnalysisLength = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHundredBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = this@HundredFragment.adapter
        }

        binding.fabAdd.setOnClickListener {
            binding.inputCard.visibility = View.VISIBLE
            binding.titleInput.requestFocus()
        }

        binding.analysisInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                previousAnalysisLength = s?.length ?: 0
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length ?: 0 > previousAnalysisLength + 1) {
                    binding.analysisInput.setSelection(s?.length ?: 0)
                }
            }

            override fun afterTextChanged(s: Editable?) {
                // Not needed
            }
        })

        binding.answerInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                previousAnswerLength = s?.length ?: 0
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length ?: 0 > previousAnswerLength + 1) {
                    binding.answerInput.setSelection(s?.length ?: 0)
                }
            }

            override fun afterTextChanged(s: Editable?) {
                // Not needed
            }
        })

        binding.confirmButton.setOnClickListener {
            val title = binding.titleInput.text.toString()
            val analysis = binding.analysisInput.text.toString()
            val answer = binding.answerInput.text.toString()
            
            if (title.isNotEmpty() && analysis.isNotEmpty() && answer.isNotEmpty()) {
                addNewQuestion(title, analysis, answer)
                binding.titleInput.text?.clear()
                binding.analysisInput.text?.clear()
                binding.answerInput.text?.clear()
                binding.inputCard.visibility = View.GONE
            }
        }

        loadQuestions()
    }

    private fun addNewQuestion(title: String, analysis: String, answer: String) {
        try {
            val externalStorageDir = android.os.Environment.getExternalStorageDirectory()
            val appFolder = File(externalStorageDir, "Interview")
            val dataFolder = File(appFolder, "data")
            val file = File(dataFolder, FileUtils.FILE_NAME)
            
            if (file.exists()) {
                val jsonString = file.readText()
                val jsonObject = JSONObject(jsonString)
                val questionsObject = jsonObject.getJSONObject("questions")
                
                // Generate a new ID (current max ID + 1)
                var maxId = 0
                for (key in questionsObject.keys()) {
                    val id = key.toIntOrNull() ?: continue
                    if (id > maxId) {
                        maxId = id
                    }
                }
                val newId = (maxId + 1).toString()
                
                // Add new question
                questionsObject.put(newId, JSONObject().apply {
                    put("title", title)
                    put("analysis", analysis)
                    put("answer", answer)
                })
                
                // Write back to file
                FileWriter(file).use { writer ->
                    writer.write(jsonObject.toString(4))
                }
                
                // Reload questions
                loadQuestions()
            } else {
                // If file doesn't exist, create it with the new question
                val jsonObject = JSONObject().apply {
                    put("questions", JSONObject().apply {
                        put("1", JSONObject().apply {
                            put("title", title)
                            put("analysis", analysis)
                            put("answer", answer)
                        })
                    })
                }
                
                file.createNewFile()
                FileWriter(file).use { writer ->
                    writer.write(jsonObject.toString(4))
                }
                
                // Reload questions
                loadQuestions()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun loadQuestions() {
        try {
            val externalStorageDir = android.os.Environment.getExternalStorageDirectory()
            val appFolder = File(externalStorageDir, "Interview")
            val dataFolder = File(appFolder, "data")
            val file = File(dataFolder, FileUtils.FILE_NAME)
            
            if (!file.exists()) {
                FileUtils.createInitialJsonFile(requireContext())
            }
            
            if (file.exists()) {
                val jsonString = file.readText()
                val jsonObject = JSONObject(jsonString)
                val questionsObject = jsonObject.getJSONObject("questions")
                val questions = mutableListOf<Question>()

                for (key in questionsObject.keys()) {
                    val questionObject = questionsObject.getJSONObject(key)
                    questions.add(
                        Question(
                            id = key,
                            title = questionObject.getString("title"),
                            analysis = questionObject.getString("analysis"),
                            answer = questionObject.getString("answer")
                        )
                    )
                }

                adapter.submitList(questions)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 